#include "stdafx.h"
#include "TCPOutputStream.h"

TCPOutputStream::TCPOutputStream(SOCKET socket): m_socket(socket), m_len(0)
{
	
}

TCPOutputStream::TCPOutputStream(const char *addr, int port): m_len(0)
{

}

TCPOutputStream::~TCPOutputStream()
{
	close();
	m_len = 0;
}

void TCPOutputStream::close()
{
	if(m_socket != INVALID_SOCKET)
	{
		closesocket(m_socket);
		m_socket = INVALID_SOCKET;
	}
}

int TCPOutputStream::write(const char* buf, int len)
{
	if(m_socket == INVALID_SOCKET)
		return -1;
	if(len <= 0)
		return -1;
	if(len + m_len < MAX_LEN)
	{
		strcat_s(m_buffer, MAX_LEN, buf);
		m_len += len;
	}
	else
	{
		int ret = flush();
		if(ret == -1)
			return -1;
		int block = len / MAX_LEN;
		for(int i = 0;i < block; ++i)
		{
			strncpy_s(m_buffer, MAX_LEN, &buf[MAX_LEN * i], MAX_LEN);
			m_len = MAX_LEN;
			ret = flush();
			if(ret == -1)
			{
				return -1;
			}
		}
		m_len = len % MAX_LEN;
		if(m_len != 0)
			strncpy_s(m_buffer, MAX_LEN, &buf[MAX_LEN * block], m_len);
	}
	return 0;
}

int TCPOutputStream::flush()
{
	if(m_socket != INVALID_SOCKET)
	{
		if(m_len > 0 && m_len <= MAX_LEN)
		{
			int ret = send(m_socket, m_buffer, m_len, 0);
			if(ret == SOCKET_ERROR)
				return -1;
			if(ret < m_len)
			{
				//loop to send the rest
			}
			return ret;
		}
		else if(m_len == 0)
			return 0;
		else
			return -1;
	}
	else
	{
		m_len = 0;
		return -1;
	}
}